<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import {
  ElButton,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElCheckbox,
  ElInputNumber,
  ElMessage
} from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { useIcon } from '@/hooks/web/useIcon'
import {
  RetrieveVarietyScopes,
  RetrieveVariety,
  CreateVariety,
  UpdateVariety
} from '@/api/sysmanage/variety'
import { VarietyItem, VarietyScopeItem } from './types/variety'
const plusIcon = useIcon({ icon: 'system-uicons:plus' })
const varietyParams = reactive({
  kw: '',
  code: '',
  scope: ''
})
const varietyList = ref<Array<VarietyItem>>([])
const varietyScopes = ref<Array<VarietyScopeItem>>([])
const editDiagParam = reactive({
  isShow: false,
  showTitle: '编辑品种',
  groupList: [
    { gid: 8, name: '金融期货' },
    { gid: 2, name: '能源化工' },
    { gid: 3, name: '有色金属' },
    { gid: 4, name: '黑色系' },
    { gid: 5, name: '农产品' }
  ],
  scopeList: varietyScopes.value,
  saveLoading: false,
  confirmButtonText: '确认添加'
})
const groupFilters = ref(
  editDiagParam.groupList.map((g) => {
    return { text: g.name, value: g.gid + '' }
  })
)
const initVarietyItem = {
  vid: -1,
  name: '',
  code: '',
  price_unit: '',
  group_id: undefined,
  scopes: [],
  is_exchange: false,
  is_active: false,
  sort_num: 1
}

const editVarietyItem = reactive(JSON.parse(JSON.stringify(initVarietyItem)))

const toShowCreateVarietyDiag = () => {
  Object.assign(editVarietyItem, initVarietyItem)
  editVarietyItem.vid = -1
  editDiagParam.showTitle = '新建品种'
  editDiagParam.confirmButtonText = '确认新建'
  editDiagParam.isShow = true
}
const toShowEditVarietyDiag = (variety: VarietyItem) => {
  Object.assign(editVarietyItem, variety)
  editVarietyItem.scopes = variety.scope.split(',')
  editVarietyItem.vid = variety.id
  editDiagParam.showTitle = '编辑品种'
  editDiagParam.confirmButtonText = '确定保存'
  editDiagParam.isShow = true
}

const filterTableRows = (value: string, row: VarietyItem) => {
  return row.group_id === parseInt(value)
}

const toSaveVarietyRow = async () => {
  editDiagParam.saveLoading = true
  editVarietyItem.scope = editVarietyItem.scopes.join(',')
  let resData: any = null
  try {
    if (editVarietyItem.vid && editVarietyItem.vid > 0) {
      resData = await UpdateVariety(editVarietyItem) // 修改
    } else {
      resData = await CreateVariety(editVarietyItem) // 新建
    }
  } catch (error) {
    editDiagParam.saveLoading = false
  }
  if (resData) {
    ElMessage.success({ message: resData.message })
    editDiagParam.saveLoading = false
    editDiagParam.isShow = false
    loadVarietyList()
  }
}

const loadVarietyList = () => {
  RetrieveVariety(varietyParams).then((res) => {
    // console.log(res)
    varietyList.value = res.data.data.map((v: VarietyItem) => {
      let scopes: Array<{ name: string; color: string }> = []
      for (let i = 0; i < varietyScopes.value.length; i++) {
        let _obj = { name: varietyScopes.value[i].name, color: '#999999' }
        for (let j = 0; j < v.scope_names.length; j++) {
          if (v.scope_names[j] === varietyScopes.value[i].name) {
            _obj.color = '#7bca53'
            break
          }
        }
        scopes.push(_obj)
      }
      v.scopeShow = scopes
      return v
    })
  })
}

onMounted(() => {
  RetrieveVarietyScopes().then((res) => {
    varietyScopes.value = res.data
    loadVarietyList()
  })
})
</script>
<template>
  <div class="page-view">
    <div class="actions-box">
      <ElButton type="primary" :icon="plusIcon" @click="toShowCreateVarietyDiag">新建</ElButton>
    </div>
    <ElTable class="table" border stripe :data="varietyList">
      <ElTableColumn prop="id" label="ID" width="100">
        <template #default="scope">
          <div class="edit-column" @click="toShowEditVarietyDiag(scope.row)">
            <Icon class="edit-icon" icon="svg-icon:box-edit" />
            <div class="row-id">{{ scope.row.id }}</div>
          </div>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="name" label="名称" width="110" />
      <ElTableColumn prop="code" label="代码" width="90" />
      <ElTableColumn prop="price_unit" label="报价单位" width="110" />
      <ElTableColumn
        prop="group_name"
        label="组别"
        width="110"
        :filters="groupFilters"
        :filter-method="filterTableRows"
      />
      <ElTableColumn label="有效空间">
        <template #default="scope">
          <span
            v-for="(s, index) in scope.row.scopeShow"
            :key="index"
            :style="{ color: s.color }"
            class="scope-tag"
            >{{ s.name }}</span
          >
        </template>
      </ElTableColumn>
      <ElTableColumn label="启用" width="70" align="center">
        <template #default="scope">
          <Icon v-if="scope.row.is_active" icon="svg-icon:dash-yes" />
        </template>
      </ElTableColumn>
      <ElTableColumn prop="sort_num" label="排序" width="70" />
    </ElTable>
    <!-- 编辑弹窗 -->
    <Dialog v-model="editDiagParam.isShow" :title="editDiagParam.showTitle">
      <ElForm>
        <ElFormItem label="中文名称">
          <ElInput v-model="editVarietyItem.name" placeholder="品种的中文名称" />
        </ElFormItem>
        <ElFormItem label="英文代码">
          <ElInput v-model="editVarietyItem.code" placeholder="品种的交易代码" />
        </ElFormItem>
        <ElFormItem label="报价单位">
          <ElInput v-model="editVarietyItem.price_unit" placeholder="报价单位" />
        </ElFormItem>
        <ElFormItem label="所属组别">
          <ElSelect v-model="editVarietyItem.group_id" style="width: 100%">
            <ElOption
              v-for="g in editDiagParam.groupList"
              :key="g.gid"
              :value="g.gid"
              :label="g.name"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="适用范围">
          <ElSelect v-model="editVarietyItem.scopes" multiple style="width: 100%">
            <ElOption v-for="s in varietyScopes" :key="s.key" :value="s.key" :label="s.name" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="排列顺序">
          <ElInputNumber v-model="editVarietyItem.sort_num" :min="1" style="width: 100%" />
        </ElFormItem>
        <ElFormItem label="市面品种">
          <ElCheckbox v-model="editVarietyItem.is_exchange">是</ElCheckbox>
        </ElFormItem>
        <ElFormItem label="是否启用">
          <ElCheckbox v-model="editVarietyItem.is_active">是</ElCheckbox>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="editDiagParam.isShow = false">关闭</ElButton>
        <ElButton @click="toSaveVarietyRow" :loading="editDiagParam.saveLoading" type="primary">
          {{ editDiagParam.confirmButtonText }}
        </ElButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped lang="less">
.page-view {
  .actions-box {
    margin-bottom: 5px;
    display: flex;
    justify-content: flex-end;
  }
  .table {
    .edit-column {
      display: flex;
      align-items: center;
      cursor: pointer;
      .edit-icon {
        margin-right: 5px;
      }
    }
    .scope-tag {
      padding: 0 2px;
    }
  }
}
</style>
